package com.atme.micromall.points.service.impl;

import com.atme.micromall.points.bean.Points;
import com.atme.micromall.points.bean.PointsExample;
import com.atme.micromall.points.bean.Record;
import com.atme.micromall.points.mapper.PointsMapper;
import com.atme.micromall.points.mapper.RecordMapper;
import com.atme.micromall.points.service.PointsService;
import com.atme.micromall.points.util.RedisLock;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class PointsServiceImpl implements PointsService {

    @Autowired
    private PointsMapper pointsMapper;

    @Autowired
    private RecordMapper recordMapper;

    @Autowired
    private RedisLock redisLock;


    /**
     * 创建积分
     * @param id
     * @return
     */
    @Override
    public int create(Integer id) {

        Points points=new Points();
        points.setMemberId(id);
        //创建赠送500积分
        points.setPoints(500);
        int count = pointsMapper.insert(points);

        return count;
    }

/*    synchronized (this){
        System.out.println();
    }*/

/*        Lock lock=new ReentrantLock();
        try {
            lock.tryLock(100, TimeUnit.MINUTES);
            System.out.println();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }*/
    /**
     * 修改积分
     * @param id
     * @param number
     * @return
     */
    @Override
    public int update(Integer id, Integer number) {
        int count=0;
        if (id==null){
            return count;
        }
        if (redisLock.lock(id.toString(),number.toString())){
            PointsExample PointsExample = new PointsExample();
            PointsExample.Criteria criteria = PointsExample.createCriteria();
            criteria.andMemberIdEqualTo(id);
            List<Points> pointsList=pointsMapper.selectByExample(PointsExample);
            Points points=pointsList.get(0);
            int pointNumber=points.getPoints();
            //积分不能扣到负数
            if (pointNumber+number<0){
                System.out.println("不能为负数");
                return count;
            }
            points.setPoints(pointNumber+number);
            count=pointsMapper.updateByPrimaryKeySelective(points);
            Record record=new Record();
            record.setPointsId(points.getId());
            record.setUpdateNumber(number);
            record.setUpdateTime(new Date());
            recordMapper.insertSelective(record);

            System.out.println("抢锁成功，执行抢锁后的内容");
            redisLock.unlock(id.toString());
            return count;
        }

        System.out.println("抢锁失败");
        return count;

    }
}
